var map;
$(document).ready(function(){
     map = new GMaps({
        div: '#map',
        lat: 11.558323,
        lng: 104.917538,
        mapTypeControlOptions: {
			style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
			position: google.maps.ControlPosition.RIGHT_BOTTOM
		},
		panControlOptions: {
			position: google.maps.ControlPosition.LEFT_CENTER
		},
		zoomControlOptions: {
			position: google.maps.ControlPosition.LEFT_CENTER
		}
    });

    if (typeof atms != "undefined"){
		var atmTemplate = $("#atmInfo").html();

		$(atms).each(function(index, atm){
		
			map.addMarker({
				lat: atm.lat,
				lng: atm.lng,
				title: atm.name,
				infoWindow: {
					content: _.template(atmTemplate, {atm:atm})
				}
			});
		});
    }
    //Fit zoom level to show all markers in the viewport.
    map.fitZoom();

    // Click on branch to filter
    $('#listBranch > li > a').on('click', function(e) {
		e.preventDefault();
		var branchId = $(this).attr('data-id');
		var isZoom = false;

		if (typeof atms != "undefined"){
			var atmTemplate = $("#atmInfo").html();

			//Delete all markers and clear the markers collection.
			map.removeMarkers();

			$(atms).each(function(index, atm){
				if (branchId === atm.branch_id) {
					
					isZoom = true;
					map.addMarker({
						lat: atm.lat,
						lng: atm.lng,
						title: atm.name,
						infoWindow: {
							content: _.template(atmTemplate, {atm:atm})
						}
					});
				}
			});
		}

		//Fit zoom level to show all markers in the viewport.
		if (isZoom) {
			map.fitZoom();
		}
    });
});